<?php

class Twis_Handler_Front extends Twis_Handler_Base
{
    public function execute()
    {
        $router = $this->getRouter();
        $request = $this->getRequest();

        // Not found
        $template = $this->getTemplate();
        if(!$template->has($router . '.html')) {
            throw new Exception('Not Found', 404);
        }

        // Handle auth
        if(!$this->_auth($request)) {
            return;
        }

        // Set template vars
        $template->set('request', $request->getQuery());
        $template->set('form', $request->getPost());

        // Process request
        if($request->isPost()) {
            $result = $this->_post();
            if($result) {
                return $result;
            }
        }
        return $template->render($router . '.html');
    }

    private function _post()
    {
        $request = $this->getRequest();
        $method = $request->getPost('_method');
        if(empty($method)) {
            throw new Exception('Undefined method name');
        }

        $template = $this->getTemplate();
        $router = $this->getRouter();

        // Get params
        $params = $request->getPost();

        // Api call
        try {
            $proxy = $this->getProxy();
            $result = $proxy->call($method, $params);
            $templateData['result'] = $result;
            $successTemplate = $router . '/success.html';
            return $template->render($successTemplate, $templateData);
        } catch (InvalidArgumentException $e) {
            $error = array();
            $error['code'] = $e->getCode();
            $error['message'] = $e->getMessage();
            $template->set('error', $error);
            return false;
        }
    }

    private function _auth()
    {
        $noAuthHandlers = array('user/login', 'user/register');
        $router = $this->getRouter();
        if(in_array($router, $noAuthHandlers)) {
            return true;
        }
        $sessionKey = $this->getSessionKey();
        $currentUser = null;
        if(!empty($sessionKey)) {
            try {
                $proxy = $this->getProxy();
                $currentUser = $proxy->call('social.user.auth', array('session_key' => $sessionKey));
            } catch(InvalidArgumentException $e) {
                $error = array();
                $error['code'] = $e->getCode();
                $error['message'] = $e->getMessage();
                $this->getTemplate()->set('error', $error);
            }
        }

        if(!$currentUser) {
            $url = $this->getUrl()->href('user/login');
            $this->getResponse()->redirect($url);
            return false;
        }
        $template = $this->getTemplate();
        $template->set('session_key', $sessionKey);
        $template->set('current_user', $currentUser);
        return true;
    }

}
